package com.example.codec;

import io.netty.buffer.ByteBuf;
import org.jboss.marshalling.ByteOutput;
import org.jboss.marshalling.Marshaller;

import java.io.IOException;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 10:14
 */
public class MarshallingEncoder {

    private static final byte[] LENGTH_PLACEHOLDER = new byte[4];

    Marshaller marshaller;

    public MarshallingEncoder() throws IOException {
        this.marshaller = MarshallingCodecFactory.buildMarshalling();
    }

    protected void encode(Object msg, ByteBuf byteBuf) throws IOException {
        try {
            // 记录长度所在位置
            final int lenPosition = byteBuf.writerIndex();
            // 长度占位符 4 个字节
            byteBuf.writeBytes(LENGTH_PLACEHOLDER);

            // 将 ByteBuf 转换为 ByteOutput 并写入数据
            final ByteOutput output = new ByteOutputAdapter(byteBuf);
            this.marshaller.start(output);
            this.marshaller.writeObject(msg);
            this.marshaller.finish();

            // 设置长度
            byteBuf.setInt(lenPosition, byteBuf.writerIndex() - lenPosition - 4);
        } finally {
            this.marshaller.close();
        }
    }

}